package org.jeecg.modules.cosmetic.handler;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.cosmetic.entity.TToxicologicalReport;
import org.jeecg.modules.cosmetic.entity.TToxicologicalSublist;
import org.jeecg.modules.cosmetic.model.dto.ToxReportChildDTO;
import org.jeecg.modules.cosmetic.model.dto.ToxSublistDTO;
import org.jeecg.modules.cosmetic.model.vo.ToxReportChildVO;
import org.jeecg.modules.cosmetic.model.vo.ToxSublistPickVO;
import org.jeecg.modules.cosmetic.model.vo.ToxSublistVO;
import org.jeecg.modules.cosmetic.service.ITToxicologicalReportService;
import org.jeecg.modules.cosmetic.service.ITToxicologicalSublistService;
import org.jeecg.modules.cosmetic.utils.CurrentUserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ToxicologicalSublistHandler {

    @Resource
    private ITToxicologicalSublistService toxicologicalSublistService;

    @Resource
    private ITToxicologicalReportService toxicologicalReportService;

    /**
     * 保存和更新模块数据
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @DS("cosmetic-datasource")
    public Result<?> saveOrUpdate(List<ToxSublistVO> list) {
        if (CollectionUtils.isEmpty(list)) return Result.error("保存或更新的数据不能为空！");
        list.forEach(m -> {
            Optional.ofNullable(m.getForm()).orElseThrow(() -> new JeecgBootException("模块标识不能为空,4-透皮吸收；5-急性毒性；6-刺激性；7-致敏性；8-光毒性；9-致突变性；10-系统毒性!"));

            // 先保存更新主表数据
            TToxicologicalSublist tToxicologicalSublist = new TToxicologicalSublist();
            BeanUtils.copyProperties(m, tToxicologicalSublist);
            tToxicologicalSublist.setUpdateBy(CurrentUserUtil.authInfo().getName());
            if (ObjectUtils.isEmpty(m.getId())) {
                tToxicologicalSublist.setCreateBy(CurrentUserUtil.authInfo().getName());
                toxicologicalSublistService.save(tToxicologicalSublist);
            } else {
                toxicologicalSublistService.updateById(tToxicologicalSublist);
            }

            // 再删除报告类型的数据，然后保存新的数据
            toxicologicalReportService.removeById(toxicologicalReportService.getOne(new LambdaQueryWrapper<TToxicologicalReport>().eq(TToxicologicalReport::getForeignId, tToxicologicalSublist.getId())
                    .eq(TToxicologicalReport::getToxId, tToxicologicalSublist.getToxId()).eq(TToxicologicalReport::getForm, tToxicologicalSublist.getForm())));
            ToxReportChildVO childVO = m.getToxReportChild();
            if (ObjectUtils.isNotEmpty(childVO)) {
                TToxicologicalReport tToxicologicalReport = new TToxicologicalReport();
                BeanUtils.copyProperties(childVO, tToxicologicalReport);
                tToxicologicalReport.setToxId(m.getToxId());
                tToxicologicalReport.setForeignId(tToxicologicalSublist.getId());
                tToxicologicalReport.setForm(m.getForm());
                toxicologicalReportService.save(tToxicologicalReport);
            }
        });
        return Result.ok();
    }

    /**
     * 查询模块的数据
     * @param id
     * @param form
     * @return
     */
    public List<ToxSublistDTO> getSublist(Long id, Integer form) {

        // 先查主表数据
        List<TToxicologicalSublist> sublistList;
        if (ObjectUtils.isEmpty(form)) {
            sublistList = toxicologicalSublistService.list(new LambdaQueryWrapper<TToxicologicalSublist>().eq(TToxicologicalSublist::getToxId, id));
        } else {
            sublistList = toxicologicalSublistService.list(new LambdaQueryWrapper<TToxicologicalSublist>().eq(TToxicologicalSublist::getToxId, id).eq(TToxicologicalSublist::getForm, form));
        }

        // 封装返回的数据集
        List<ToxSublistDTO> list = Lists.newArrayList();
        return sublistList.stream().map(m -> {
            ToxSublistDTO dto = new ToxSublistDTO();
            BeanUtils.copyProperties(m, dto);

            // 查询报告数据
            TToxicologicalReport report = toxicologicalReportService.getOne(new LambdaQueryWrapper<TToxicologicalReport>().eq(TToxicologicalReport::getForeignId, m.getId()).eq(TToxicologicalReport::getForm, form).eq(TToxicologicalReport::getToxId, id));
            if (ObjectUtils.isNotEmpty(report)) {
                ToxReportChildDTO reportDTO = new ToxReportChildDTO();
                BeanUtils.copyProperties(report, reportDTO);
                dto.setToxReportChild(reportDTO);
            }
            return dto;
        }).collect(Collectors.toCollection(() -> list));
    }

    /**
     * 查询模块下的优选数据
     * @param id
     * @param form
     * @return
     */
    public Long getSublistPick(Long id, Integer form) {
        TToxicologicalSublist toxicologicalSublist = toxicologicalSublistService.getOne(new LambdaQueryWrapper<TToxicologicalSublist>().eq(TToxicologicalSublist::getToxId, id).eq(TToxicologicalSublist::getForm, form).eq(TToxicologicalSublist::getPick, 0));
        if (ObjectUtils.isEmpty(toxicologicalSublist)) {
            return 0L;
        }
        return toxicologicalSublist.getId();
    }

    /**
     * 更新优选和取消优选
     * @param voList
     * @return
     */
    public Result<?> updateSublistPick(List<ToxSublistPickVO> voList) {
        if (CollectionUtils.isEmpty(voList)) {
            return Result.error("参数不能为空");
        } else if (ObjectUtils.isEmpty(voList.get(0).getId())) {
            return Result.error("数据未保存，请先保存数据！");
        }
        voList.forEach(m -> {
            TToxicologicalSublist toxicologicalSublist = toxicologicalSublistService.getOne(new LambdaQueryWrapper<TToxicologicalSublist>().eq(TToxicologicalSublist::getId, m.getId()));
            toxicologicalSublist.setPick(m.getPick());
            toxicologicalSublistService.updateById(toxicologicalSublist);
        });
        return Result.ok();
    }

    /**
     * 删除模块数据
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @DS("cosmetic-datasource")
    public boolean delete(Long id) {
        TToxicologicalSublist toxicologicalSublist = toxicologicalSublistService.getById(id);
        Optional.ofNullable(toxicologicalSublist).orElseThrow(() -> new JeecgBootException("模块数据为空！"));
        toxicologicalReportService.removeById(toxicologicalReportService.getOne(new LambdaQueryWrapper<TToxicologicalReport>()
                .eq(TToxicologicalReport::getForeignId, id).eq(TToxicologicalReport::getToxId, toxicologicalSublist.getToxId()).eq(TToxicologicalReport::getForm, toxicologicalSublist.getForm())));
        return toxicologicalSublistService.removeById(toxicologicalSublist);
    }

}
